<template>
    <div>
        <el-card class="box-card">
            <!-- 卡片 -->
            <el-button type="primary" size="default" icon="Plus" @click="addTrademark">添加品牌</el-button>
            <!-- 表格
                border:纵向边框
                label:列标题
                align:列的对齐方式
            -->
            <el-table style="margin: 10px 0;" border :data="trademarkArr">
                <el-table-column label="序号" width="80px" align="center" type="index"></el-table-column>
                <el-table-column label="品牌名称" prop="tmName"></el-table-column>
                <el-table-column label="品牌LOGO">
                    <template #="{row,$index}">
                        <img :src="row.logoUrl" alt="" style="width: 100px;height: 100px;">
                    </template>
                </el-table-column>
                <el-table-column label="品牌操作">
                    <template #="{row,$index}">
                        <el-button type="primary" size="small" icon="Edit" @click="updateTrademark(row)"></el-button>
                        <el-popconfirm :title="`您确定要删除${row.tmName}?`" width="250px" icon="Delete" @confirm="removeTradeMark(row.id)">
                            <template #reference>
                                <el-button type="primary" size="small" icon="Delete"></el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页器
                pagination
                    v-model:current-pag 设置分页器的当前页码
                    v-model:page-size:一页几条
                    page-sizes:每一页显示几条的选择
                    layout:可以设置分页器的六个子组件的布局调整
            -->
            <el-pagination
            :pager-count="9"
            v-model:current-page="pageNo"
            v-model:page-size="limit"
            :page-sizes="[3, 5, 7, 9]"
            :background="true "
            layout=" prev, pager, next, jumper,->, sizes,total"
            :total="total"
            @current-change="getHasTrademark"
            @size-change="sizeChange"
            />
        </el-card>
        <!-- 对话框 -->
        <el-dialog v-model="dialogFormVisible" :title="trademarkParams.id ? '修改品牌' : '添加品牌'">
            <el-form style="width: 80%;" :model="trademarkParams" :rules="rules" ref="formRef">
                <el-form-item label="品牌名称" label-width="100" prop="tmName">
                    <el-input placeholder="请您输入品牌名称" v-model="trademarkParams.tmName"></el-input>
                </el-form-item>
                <el-form-item label="品牌LOGO" label-width="100" prop="logoUrl">
                    <el-upload
                        class="avatar-uploader"
                        action="/api/admin/product/fileUpload"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload"
                    > 
                        <img v-if="trademarkParams.logoUrl" :src="trademarkParams.logoUrl" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                    </el-upload>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button type="primary" size="default" @click="cancel">取消</el-button>
                <el-button type="primary" size="default" @click="confirm">确认</el-button>
            </template>
        </el-dialog>
    </div>
</template>
<script lang="ts" setup>
import { ElMessage, type UploadProps } from 'element-plus'
import {onMounted, reactive, ref,nextTick} from 'vue'
import {reqHasTrademark,reqAddOrUpdateTrademark,reqDeleteTrademark} from '@/api/product/trademark'
import type {Records,TrademarkResponseData,TradeMark} from '@/api/product/trademark/type'
let pageNo = ref<number>(1)
let limit = ref<number>(3)
// 已有品牌总数
let total = ref<number>(0)
let trademarkArr = ref<Records>([])
let dialogFormVisible = ref<boolean>(false)
let trademarkParams = reactive<TradeMark>({
    tmName:'',
    logoUrl:''
})
let formRef = ref()
const getHasTrademark = async (pager=1) => {
    pageNo.value = pager
    let result:TrademarkResponseData = await reqHasTrademark(pageNo.value,limit.value)
    // console.log(result)
    if(result.code == 200){
        total.value = result.data.total
        trademarkArr.value = result.data.records
    }
}
// 分页器当前页码发生变化的时候出发
// const changePageNo = () => {
//     // 当前页码发生变化的时候 再次发请求
//     getHasTrademark()
// }
const sizeChange = () => {
    // 当前每一页的数据量发生变化的时候，当前页码归1
    // pageNo.value = 1
    getHasTrademark()
}
// 添加品牌
const addTrademark = () => {
    trademarkParams.id = 0
    trademarkParams.logoUrl = ''
    trademarkParams.tmName = ''
    dialogFormVisible.value = true 
    // 第一种写法：ts的问好语法
    // formRef.value?.clearValidate('tmName')
    // formRef.value?.clearValidate('logoUrl')
    nextTick(()=>{
        formRef.value?.clearValidate('tmName')
        formRef.value?.clearValidate('logoUrl')
    })
}
//修改品牌
const updateTrademark = (row:TradeMark) => {
    // trademarkParams.id = row.id
    // trademarkParams.tmName = row.tmName
    // trademarkParams.logoUrl = row.logoUrl
    // 以上三句等同于以下一句
    Object.assign(trademarkParams,row)
    console.log(row)
    dialogFormVisible.value = true
    nextTick(()=>{
        formRef.value?.clearValidate('tmName')
        formRef.value?.clearValidate('logoUrl')
    })
}
const cancel = ()=>{
    dialogFormVisible.value = false
}
const confirm = async ()=>{
    // 在你发请求之前，要对整个表单进行校验
    // 调用这个方法进行全部的表单验证，如果校验全部通过，在执行后面的语句
    await formRef.value.validate()
    let result:any = await reqAddOrUpdateTrademark(trademarkParams)
    if(result.code == 200){
        dialogFormVisible.value = false
        ElMessage({
            type:'success',
            message:trademarkParams.id?'修改品牌成功':'添加品牌成功'
        })
        getHasTrademark(trademarkParams.id?pageNo.value:1)
    }else{
        ElMessage({
            type:'error',
            message:trademarkParams.id?'修改品牌失败':'添加品牌失败',
        })
        dialogFormVisible.value = false
    }
    
}
// 上传图片组件->上传图片之前触发的钩子函数
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    //   钩子是在图片上传成功之前触发 上传文件之前可以约束文件类型和大小
    // 要求：上传文件格式png|jpg|gif 4M
    if(rawFile.type == 'image/png'||rawFile.type == 'image/jpeg'||rawFile.type == 'image/gif'){
        if(rawFile.size/1024/1024 < 4){
            return true
        }else{
            ElMessage({
                type:'error',
                message:'上传文件的大小小于4M'
            })
            return false
        }
    }else{
        ElMessage({
            type:'error',
            message:'上传的文件格式必须为PNG|JPG|GIF'
        })
        return false
    }
}
// 图片上传成功
const handleAvatarSuccess: UploadProps['onSuccess'] = (response,uploadFile) => {
    // response:即为当前这次上传图片的post请求服务器返回的数据
    trademarkParams.logoUrl = response.data
    // 图片上传成功，清除掉对应图片的校验结果
    formRef.value.clearValidate('logoUrl')
}
onMounted(()=>{
    getHasTrademark()
})
// 品牌自定义校验规则的方法
const validatorTmName = (rule:any,value:any,callback:any) => {
    if(value.trim().length>=2){
        callback()
    }else{
        callback(new Error('品牌名称位数大于等于两位'))
    }
}
const validatorLogoUrl = (rule:any,value:any,callback:any) => {
    if(value){
        callback()
    }else{
        callback(new Error('LOGO图片务必上传'))
    }
}
// 定义表单校验规则对象
const rules = {
    tmName:[
        {required:true,trigger:'blur',validator:validatorTmName}
    ],
    logoUrl:[
        {required:true,validator:validatorLogoUrl}
    ]
}
const removeTradeMark = async (id:number) => {
    let result = await reqDeleteTrademark(id)
    if(result.code == 200){
        ElMessage({
            type:'success',
            message:'删除品牌成功'
        })
        getHasTrademark(trademarkArr.value.length>1? pageNo.value:pageNo.value-1)
    }else{
        ElMessage({
            type:'error',
            message:'删除品牌失败'
        })
    }
}
</script>
<style scoped lang="scss"></style>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>